package com.shunwang.errors.client.spring;

import java.io.IOException;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.shunwang.errors.engine.builder.annotation.LoggerHandlerAnnotationParser;
import com.shunwang.errors.engine.builder.xml.LoggerXmlParser;
import com.shunwang.errors.engine.core.ErrorsHandler;

public class ErrorsHandlerAnnotationFactoryBean implements FactoryBean, InitializingBean{
	private Resource configLocation;
	private ErrorsHandler handler;
	
	public Object getObject() throws Exception {
		return handler;
	}

	public Class getObjectType() {
		return handler == null? ErrorsHandler.class:handler.getClass();
	}

	public boolean isSingleton() {
		return true;
	}

	public void afterPropertiesSet() throws Exception {
		handler = buildHandler();
	}

	private ErrorsHandler buildHandler() throws IOException {
		if(configLocation == null)
            throw new IllegalArgumentException("At least 1 'configLocation' entry is required");
		
		ErrorsHandler client = null;
		try {
			client = new LoggerHandlerAnnotationParser(configLocation.getFile()).parser();
		} catch (Exception e) {
			throw new NestedIOException("Failed to parse config resource: " + configLocation, e.getCause());
		}
            
		return client;
	}

    public Resource getConfigLocation() {
        return configLocation;
    }

    public void setConfigLocation(Resource configLocation) {
        this.configLocation = configLocation;
    }


}
